package com.beiye.drivertransport.safelearn;


import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.beiye.drivertransport.R;
import com.beiye.drivertransport.bean.QuestionInvestigationBean;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.MessageEventTest2;
import com.example.mylibrary.paper.utils.DensityUtils;
import com.example.mylibrary.paper.utils.QuestionAnswerUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;


/**
 * 问卷调查题目
 */
public class QuestionInvestigationFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private boolean isViewCreate;//view是否已创建
    private boolean isViewVisible;//fragment是否可见
    ArrayList<String> opitionList = new ArrayList<>();
    ArrayList<Integer> checkboxList = new ArrayList<>();
    private int position;
    private View view;
    private QuestionInvestigationBean.DataBean.UqItemListBean rowsBean;
    // private Animation animation;


    public QuestionInvestigationFragment() {
    }

    public static QuestionInvestigationFragment newInstance(QuestionInvestigationBean.DataBean.UqItemListBean rowsBean, int position) {
        QuestionInvestigationFragment fragment = new QuestionInvestigationFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, rowsBean);
        args.putSerializable(ARG_PARAM2, position);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isViewVisible = true;
            lazyLoad();
        } else {
            isViewVisible = false;
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.daikaotest_item1, container, false);
        if (getArguments() != null) {
            rowsBean = (QuestionInvestigationBean.DataBean.UqItemListBean) getArguments().getSerializable(ARG_PARAM1);
            position = getArguments().getInt(ARG_PARAM2);
        }
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreate = true;
        lazyLoad();
    }

    private void lazyLoad() {
        if (isViewCreate && isViewVisible) {
            initView();
        }
    }

    private void initView() {
        int sn = rowsBean.getSn();

        if (rowsBean.getUserOption() == null) {
            SharedPreferences sp = getActivity().getSharedPreferences("DailyTrainingExaminationActivity",
                    Context.MODE_PRIVATE);
            String checkboxopition = sp.getString("checkboxopition" + sn, "");
            String radioopition = sp.getString("radioopition" + sn, "");
            EventBus.getDefault().post(new MessageEventTest2(1, checkboxopition, sn, radioopition,""));
        } else {
            if (rowsBean.getFillType() == 3 || rowsBean.getFillType() == 1) {
                EventBus.getDefault().post(new MessageEventTest2(1, "", sn, rowsBean.getUserOption(),""));
            } else if (rowsBean.getFillType() == 2) {
                SharedPreferences sp = getActivity().getSharedPreferences("DailyTrainingExaminationActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("checkboxopition" + sn, rowsBean.getUserOption());
                edit.commit();
                EventBus.getDefault().post(new MessageEventTest2(1, rowsBean.getUserOption(), sn, "",""));
            }
        }
        TextView tv_desc = (TextView) view.findViewById(R.id.tv_daikao_test);
        ImageView img_daikao = (ImageView) view.findViewById(R.id.img_daikao_test_item);
        
        String optionA = rowsBean.getOptionA();
        String optionB = rowsBean.getOptionB();
        String optionC = rowsBean.getOptionC();
        String optionD = rowsBean.getOptionD();
        String optionE = rowsBean.getOptionE();
        String optionF = rowsBean.getOptionF();

        opitionList.clear();
        opitionList.add(optionA);
        opitionList.add(optionB);
        opitionList.add(optionC);
        opitionList.add(optionD);
        opitionList.add(optionE);
        opitionList.add(optionF);
        ArrayList<String> opitionnewList = new ArrayList<>();
        opitionnewList.clear();
        for (int i = 0; i < opitionList.size(); i++) {
            if (opitionList.get(i) != null && !opitionList.get(i).equals("")) {
                opitionnewList.add(opitionList.get(i));
            }
        }
        int question_select1 = rowsBean.getQuestion_select1();
        int question_select2 = rowsBean.getQuestion_select2();
        int question_select3 = rowsBean.getQuestion_select3();
        int question_select4 = rowsBean.getQuestion_select4();
        int question_select5 = rowsBean.getQuestion_select5();
        int question_select6 = rowsBean.getQuestion_select6();
        checkboxList.clear();
        checkboxList.add(question_select1);
        checkboxList.add(question_select2);
        checkboxList.add(question_select3);
        checkboxList.add(question_select4);
        checkboxList.add(question_select5);
        checkboxList.add(question_select6);
        ArrayList<Integer> checkboxListnew = new ArrayList<>();
        checkboxListnew.clear();
        for (int i = 0; i < opitionnewList.size(); i++) {
            checkboxListnew.add(checkboxList.get(i));
        }

        String tag = QuestionInvestigationBean.getQuestionTypeStr(rowsBean.getFillType());
        CharSequence content = tag + ". " + rowsBean.getItemTitle();
        SpannableStringBuilder builder = new SpannableStringBuilder(content);
        builder.setSpan(new ImageSpan(getActivity(), R.drawable.text_background) {
            @Override
            public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
                paint.setColor(Color.parseColor("#1F80C4"));
                paint.setTextSize(DensityUtils.sp2px(getContext(), 11));
                canvas.drawText(text.subSequence(start, end).toString(), x + DensityUtils.dp2px(getContext(), 5), y - DensityUtils.dp2px(getContext(), 3), paint);
                super.draw(canvas, text, start, end, x, top, y, bottom - DensityUtils.dp2px(getContext(), 1), paint);
            }
        }, 0, tag.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_desc.setText(builder);

        if (rowsBean.getFillType() == QuestionInvestigationBean.TYPE_Multiple_Choice) {//多项选择题
            updateCheckBoxView(opitionnewList, sn, checkboxListnew);
        } else if (rowsBean.getFillType() == QuestionInvestigationBean.TYPE_True_OR_False) {//判断题
            updateRadioView(opitionnewList, sn);
        } else if (rowsBean.getFillType() == QuestionInvestigationBean.TYPE_Single_Choice) {//单选题
            updateRadioView(opitionnewList, sn);
        }else if(rowsBean.getFillType()==QuestionInvestigationBean.TYPE_INPUT){ //文本输入框
            updateInputView(opitionnewList,sn);
        }
    }

    //字母排序
    public String sortString(String str) {
        //  System.out.println("排序前的字符串是:" + str);
        LogUtils.e("排序前的字符串是:", str);
        // 排序前字符串转换为字符数组
        char[] cs = str.toCharArray();

        // 升序排序
        for (int i = 0; i < cs.length - 1; i++) {
            for (int j = 0; j < cs.length - 1 - i; j++) {
                char temp = 0;
                if (cs[j] > cs[j + 1]) {
                    temp = cs[j];
                    cs[j] = cs[j + 1];
                    cs[j + 1] = temp;
                }
            }
        }

        // 排序以后的字符串
        String newString = "";
        for (int i = 0; i < cs.length; i++) {
            newString += cs[i];
        }
        // 打印排序以后的字符串
        LogUtils.e("排序后的字符串是:", newString);
        return newString;

    }

    /**
     * 添加多选按钮
     *
     * @param
     * @param opitionnewList
     * @param sn
     * @param checkboxListnew
     */
    private void updateCheckBoxView(ArrayList<String> opitionnewList, final int sn, ArrayList<Integer> checkboxListnew) {
        final LinearLayout layout = (LinearLayout) view.findViewById(R.id.check_options);
        layout.removeAllViews();
        for (int i = 0; i < opitionnewList.size(); i++) {
            String opition = opitionnewList.get(i);
            CheckBox checkboxView = (CheckBox) LayoutInflater.from(getActivity()).inflate(R.layout.item_checkbox_new, null);
            checkboxView.setText(QuestionAnswerUtils.getAnswerStr(i) + opition);
            checkboxView.setTag(i);
            if (checkboxListnew.get(i) == i) {
                checkboxView.setChecked(true);
            } else {
                checkboxView.setChecked(false);
            }

            checkboxView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        SharedPreferences sp = getActivity().getSharedPreferences("DailyTrainingExaminationActivity",
                                Context.MODE_PRIVATE);
                        String s2 = sp.getString("checkboxopition" + sn, "");
                        int op = (int) buttonView.getTag();
                        StringBuffer s1 = new StringBuffer(s2);
                        if (op == 0) {
                            s1.append("A");
                            rowsBean.setQuestion_select1(0);
                        } else if (op == 1) {
                            s1.append("B");
                            rowsBean.setQuestion_select2(1);
                        } else if (op == 2) {
                            s1.append("C");
                            rowsBean.setQuestion_select3(2);
                        } else if (op == 3) {
                            s1.append("D");
                            rowsBean.setQuestion_select4(3);
                        } else if (op == 4) {
                            s1.append("E");
                            rowsBean.setQuestion_select5(4);
                        } else if (op == 5) {
                            s1.append("F");
                            rowsBean.setQuestion_select6(5);
                        }
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("checkboxopition" + sn, s1.toString());
                        edit.putInt("sn", sn);
                        edit.commit();
                        EventBus.getDefault().post(new MessageEventTest2(1, s1.toString(), sn, "",""));
                    } else {
                        SharedPreferences sp = getActivity().getSharedPreferences("DailyTrainingExaminationActivity",
                                Context.MODE_PRIVATE);
                        String checkboxopition = sp.getString("checkboxopition" + sn, "");
                        int op = (int) buttonView.getTag();
                        String checkboxopitionnew = "";
                        if (op == 0) {
                            checkboxopitionnew = checkboxopition.replace("A", "");
                            rowsBean.setQuestion_select1(-1);

                        } else if (op == 1) {
                            checkboxopitionnew = checkboxopition.replace("B", "");
                            rowsBean.setQuestion_select2(-1);

                        } else if (op == 2) {
                            checkboxopitionnew = checkboxopition.replace("C", "");
                            rowsBean.setQuestion_select3(-1);

                        } else if (op == 3) {
                            checkboxopitionnew = checkboxopition.replace("D", "");
                            rowsBean.setQuestion_select4(-1);

                        } else if (op == 4) {
                            checkboxopitionnew = checkboxopition.replace("E", "");
                            rowsBean.setQuestion_select5(-1);

                        } else if (op == 5) {
                            checkboxopitionnew = checkboxopition.replace("F", "");
                            rowsBean.setQuestion_select6(-1);

                        }
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("checkboxopition" + sn, checkboxopitionnew);
                        edit.putInt("sn", sn);
                        edit.commit();
                        EventBus.getDefault().post(new MessageEventTest2(1, checkboxopitionnew, sn, "",""));
                    }


                }
            });

            layout.addView(checkboxView);
        }

    }

    /**
     * 添加单选按钮
     *
     * @param opitionnewList
     * @param
     */
    private void updateRadioView(final ArrayList<String> opitionnewList, final int sn) {
        final RadioGroup layout = (RadioGroup) view.findViewById(R.id.rg_options);
        layout.removeAllViews();
        int checkId = -1;
        for (int i = 0; i < opitionnewList.size(); i++) {
            final String opition = opitionnewList.get(i);
            final RadioButton radioView = (RadioButton) LayoutInflater.from(getActivity()).inflate(R.layout.item_radio_new, null, true);
            final RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT);
            radioView.setLayoutParams(layoutParams);
            radioView.setText(QuestionAnswerUtils.getAnswerStr(i) + opition);
            radioView.setTag(i);
            radioView.setId(i);
            if (rowsBean.getQuestion_select() == i) {
                checkId = i;
            }

            radioView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        int op = (int) buttonView.getTag();
                        String radioopition = "";
                        SharedPreferences sp = getActivity().getSharedPreferences("DailyTrainingExaminationActivity",
                                Context.MODE_PRIVATE);
                        //   int apromptMark = sp.getInt("apromptMark", 0);
                        if (op == 0) {
                            radioopition = "A";
                            rowsBean.setQuestion_select(0);
                        } else if (op == 1) {
                            radioopition = "B";
                            rowsBean.setQuestion_select(1);
                        } else if (op == 2) {
                            radioopition = "C";
                            rowsBean.setQuestion_select(2);
                        } else if (op == 3) {
                            radioopition = "D";
                            rowsBean.setQuestion_select(3);
                        } else if (op == 4) {
                            radioopition = "E";
                            rowsBean.setQuestion_select(4);
                        } else if (op == 5) {
                            radioopition = "F";
                            rowsBean.setQuestion_select(5);
                        }
                        radioView.setChecked(true);

                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("radioopition" + sn, radioopition);
                        edit.putInt("sn", sn);
                        edit.commit();
                        EventBus.getDefault().post(new MessageEventTest2(1, "", sn, radioopition,""));

                    }
                }
            });
            layout.addView(radioView);
        }
        if (checkId != -1) {
            layout.clearCheck();
            layout.check(checkId);

        }
    }

    //添加输入框
    private void updateInputView(ArrayList<String> opitionnewList, final int sn) {
        LinearLayout layout = (LinearLayout) view.findViewById(R.id.edit_options);
        layout.setBackgroundResource(R.drawable.stroke_gray_5);
        layout.removeAllViews();


        EditText editTextLayout= (EditText) LayoutInflater.from(getActivity()).inflate(R.layout.item_editlayout,null,false);
        layout.addView(editTextLayout);


        LogUtils.e("测试", "updateInputView: "+rowsBean.getUserOption());
        if(rowsBean.getUserOption()!=null){
            editTextLayout.setText(rowsBean.getUserOption());
        }

        editTextLayout.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                SharedPreferences sp = getActivity().getSharedPreferences("DailyTrainingExaminationActivity", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("editoption" + sn, editTextLayout.getText().toString().trim());
                edit.putInt("sn", sn);
                edit.commit();
                EventBus.getDefault().post(new MessageEventTest2(1, "", sn,"", editTextLayout.getText().toString().trim()));
            }
        });
    }
}
